package com.example.mcp;

import android.content.Context;
import android.os.PowerManager;
import android.util.Log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 电源锁管理器
 * 防止 CPU 休眠，确保 MCP 服务器持续运行
 */
public class WakeLockManager {
    
    private static final Logger logger = LoggerFactory.getLogger(WakeLockManager.class);
    private static final String TAG = "WakeLockManager";
    private static final String WAKE_LOCK_TAG = "MCP_SERVER_WAKE_LOCK";
    
    private PowerManager.WakeLock wakeLock;
    private Context context;
    private boolean isWakeLockAcquired = false;
    
    public WakeLockManager(Context context) {
        this.context = context;
    }
    
    /**
     * 获取电源锁
     * 使用 PARTIAL_WAKE_LOCK 保持 CPU 运行，但允许屏幕关闭
     */
    public boolean acquireWakeLock() {
        if (isWakeLockAcquired) {
            logger.warn("⚠️ 电源锁已经获取");
            return true;
        }
        
        try {
            PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (powerManager != null) {
                // 使用 PARTIAL_WAKE_LOCK 保持 CPU 运行，但允许屏幕关闭
                // 这样既节省电池，又确保服务器运行
                wakeLock = powerManager.newWakeLock(
                    PowerManager.PARTIAL_WAKE_LOCK,
                    WAKE_LOCK_TAG
                );
                
                wakeLock.acquire();
                isWakeLockAcquired = true;
                logger.info("🔋 电源锁已获取 - CPU 将保持运行状态");
                return true;
            } else {
                logger.error("❌ 无法获取 PowerManager 服务");
                return false;
            }
        } catch (Exception e) {
            logger.error("❌ 获取电源锁失败", e);
            return false;
        }
    }
    
    /**
     * 释放电源锁
     */
    public void releaseWakeLock() {
        if (wakeLock != null && isWakeLockAcquired) {
            try {
                wakeLock.release();
                isWakeLockAcquired = false;
                logger.info("🔋 电源锁已释放");
            } catch (Exception e) {
                logger.error("❌ 释放电源锁失败", e);
            }
        }
    }
    
    /**
     * 检查电源锁状态
     */
    public boolean isWakeLockAcquired() {
        return isWakeLockAcquired && wakeLock != null && wakeLock.isHeld();
    }
    
    /**
     * 获取电源锁状态信息
     */
    public String getWakeLockStatus() {
        if (isWakeLockAcquired()) {
            return "电源锁已获取 - CPU 保持运行";
        } else {
            return "电源锁未获取 - CPU 可能休眠";
        }
    }
    
    /**
     * 清理资源
     */
    public void cleanup() {
        releaseWakeLock();
        wakeLock = null;
    }
}
